﻿var FileManger = {
    o: {
        skin: "",               //皮肤风格["","green","blue","yellow"]
        filter: [],             //筛选器
        dest: "",               //目的地
        savePath: "",           //保存路径
        plate: [],              //要使用的板块，默认使用所有模块
        multiple: false,        //是否允许同时选择多个文件，此功能暂时禁用
        maxCount: null,
        mode: 0,                //模式,0:显示网络资源和本地资源，1：只显示本地资源
        saveMode: 0,            //保存模式：0：保存在新建日期文件夹下，1:直接保存在当前文件夹下
        back: null              //回调函数
    },

    constant: {
        topLayer: "#tplayer",                              //顶层遮盖层
        topLayerCss: "tplayer",                            //顶层遮盖层基础样式
        fiManger: "#fiManger",                             //文件管理浮层
        fiMangerCss: "fimanger",                           //文件管理浮层基础样式
        fiSource: "#fiSource",                             //文件资源浮层
        fiSourceCss: "fimanger sour",                      //文件资源浮层基础样式
        webFile: "#webFile",                               //
        locFile: "#locFile",
        mod: { web: "webFile", loc: "locFile" },           //文件模式
        fiTopNav: "#fitpnav",
        fiUploader: "#fiUploader",                         //文件上传控件
        fiUploaderId: "fiUploader",                        //文件上传控件id名
        locFiName: "#locFiName",
        fileList: "#fileList",
        backPath: "#backPath",                             //上一层路径
        fiConfirm: "#fiConfirm",
        fiSelect: "#fiSelect",
        fiResize: "#fiResize",
        fiUrl: "#fiUrl",
        fiDesc: "#fiDesc",
        fiDesc0: "#fiDesc0",
        fiAddrList: "#fiAddrList",
        curCss: "cur",
        rootPath: "/u",
        file: "file",
        folder: "folder",                                   //文件夹标识
        ajaxUrl: "x/ajax.ashx",                             //服务器地址
        ok: '<b class="iconfont">&#xf00c;</b>',             //OK图标           
        minimize: '<b class="iconfont">&#xf066;</b>',       //最小化图标
        maximize: '<b class="iconfont">&#xf065;</b>',       //最大化图标
        minHeight: 414,                                     //文件资源列表框最小高度
        subHeight: 140,                                     //
        locFileList: [],                                    //选中的本地文件列表
        errFileList: [],                                    //错误文件列表
        sizeMode: {
            max: "max",
            min: "min"
        },
        errMessage: {
            em0: "请选择文件！"
        },
        html: {
            tplayer: '<div class="tplayer" id="tplayer"></div>',
            fiManger: {
                hd: '<div class="fimanger" id="fiManger"><div class="hd clearfix "><span class="tit" id="fmTitle">文件管理</span> <span class="close" onclick="FileManger.close();">×</span></div><div class="bd"><ul class="tnav clearfix" id="fitpnav">',
                web: '<li nid="webFile"><span>网络资源</span></li>',
                loc: '<li nid="locFile"><span>本地资源</span></li></ul>',
                bd0: '<div class="main">',
                webFile: '<ul class="tabl clearfix" id="webFile" style="display: none;"><li><div class="t"> 文件地址：</div><div class="d"><input type="text" class="fitxt furl" id="fiUrl" /><a class="fibtn fsour" onclick="FileManger.openSource();">文件资源</a></div></li><li><div class="t"> 文件说明：</div><div class="d"><input type="text" class="fitxt fdes" id="fiDesc" /></div></li></ul>',
                locFile: '<ul class="tabl clearfix" id="locFile" style="display: none;"><li><div class="t">文件地址：</div><div class="d">',
                bm: '</div></div><div class="bm clearfix"><a class="fibtn" onclick="FileManger.close();">取消</a> <a class="fibtn" id="fiConfirm" mod="" onclick="FileManger.confirmSelection();">选择</a></div></div>',
                fi0: '<div class="ficont"><a class="fibtn" onclick="FileManger.openFiView();">浏览...</a><input type="file" name="fiUploader" id="fiUploader" onchange="FileManger.getLocFileName();" /></div><ul class="addrs clearfix" id="fiAddrList"></ul></div></li></ul>',
                fi1: '<div class="ficont1"><input type="file" name="fiUploader" id="fiUploader"/></div></li></ul>'
            },
            fiSource: {
                hd: '<div class="fimanger sour" id="fiSource"><div class="hd clearfix"><span class="tit">文件空间</span><span class="icon c" onclick="FileManger.closeSource();"><b class="iconfont">&#xf057;</b></span><span class="icon" smod="min" id="fiResize" onclick="FileManger.resize();"><b class="iconfont">&#xf065;</b></span></div>',
                bm: '<div class="bm clearfix"><a class="fibtn" onclick="FileManger.closeSource();">取消</a> <a class="fibtn" id="fiSelect" p="" onclick="FileManger.select();">选择</a></div></div>',
                bd: '<div class="bd" id="fisbox"><div class="tnav clearfix"><a class="back" id="backPath" back="" onclick="FileManger.toBack(this);">返回上一层</a></div><div class="main"><ul class="flist clearfix" id="fileList"></ul></div></div>'
            }
        }
    },

    open: function (o) {
        var _ = this;
        _.o = $.extend(_.o, o);
        _.constant.rootPath = _.o.savePath == null || _.o.savePath == "" ? _.constant.rootPath : _.o.savePath;
        var fmhtml = "";
        var html = _.constant.html.fiManger;
        var brow = $.browser;
        var version = parseInt(brow.version);
        //如果是ie9一下的版本

        if (_.o.mode == 0) {
            if (brow.msie && version < 9.0) {
                fmhtml = html.hd + html.web + html.loc + html.bd0 + html.webFile + html.locFile + html.fi1 + html.bm;
            }
            else {
                fmhtml = html.hd + html.web + html.loc + html.bd0 + html.webFile + html.locFile + html.fi0 + html.bm;
            }
        }
        else {

            if (brow.msie && version < 9.0) {
                fmhtml = html.hd + html.loc + html.bd0 + html.locFile + html.fi1 + html.bm;
            }
            else {
                fmhtml = html.hd + html.loc + html.bd0 + html.locFile + html.fi0 + html.bm;
            }
        }

        $(document.body).append(_.constant.html.tplayer);
        $(document.body).append(fmhtml);

        $(_.constant.topLayer).addClass(_.o.skin);
        $(_.constant.fiManger).addClass(_.o.skin);

        $(_.constant.fiUploader).attr("multiple", _.o.multiple);
        _.tabSwitch();
    },

    close: function () {
        var _ = this;
        $(_.constant.topLayer).remove();
        $(_.constant.fiManger).remove();
    },

    openSource: function () {
        var _ = this;
        var fshtml = _.constant.html.fiSource.hd + _.constant.html.fiSource.bd + _.constant.html.fiSource.bm;
        $(document.body).append(fshtml);
        $(_.constant.fiSource).addClass(_.o.skin);
        //加载数据
        _.getFileList(_.constant.rootPath);
    },

    closeSource: function () {
        var _ = this;
        $(_.constant.fiSource).remove();
    },

    //标签切换
    tabSwitch: function () {
        var _ = this;
        //初始化
        $(_.constant.fiTopNav).children("li:eq(0)").addClass("cur");
        var n = $(_.constant.fiTopNav).children("li:eq(0)").attr("nid");
        if (n != null && n !== "") {
            $("#" + n).css("display", "block");
            $(_.constant.fiConfirm).attr("mod", n);
        }
        $(_.constant.fiTopNav).children("li").unbind("click");

        //绑定事件
        $(_.constant.fiTopNav).children("li").click(function () {

            if ($(this).hasClass(_.constant.curCss)) {
                return;
            }
            var navId = $(this).attr("nid") ? $(this).attr("nid") : "";
            $(_.constant.fiTopNav).children("li").each(function () {
                var nid = $(this).attr("nid") ? $(this).attr("nid") : "";
                if (navId != nid && $(this).hasClass(_.constant.curCss)) {
                    $(this).removeClass(_.constant.curCss);
                    $("#" + nid).css("display", "none");
                }
                else {
                    $(this).addClass(_.constant.curCss);
                    $("#" + navId).css("display", "block");
                    $(_.constant.fiConfirm).attr("mod", navId);
                }
            });
        });
    },

    openFiView: function () {
        var _ = this;
        $(_.constant.fiUploader).click();
    },

    getLocFileName: function () {
        var _ = this;
        _.constant.errFileList = [];
        _.constant.locFileList = [];
        var fileUploader = document.getElementById(_.constant.fiUploaderId);
        var fileList = fileUploader.files;
        for (var i = 0; i < fileList.length; i++) {
            if (_.o.maxCount && i >= _.o.maxCount) {
                alert("每次最多允许上传" + _.o.maxCount.toString() + "个文件！");
                break;
            }
            var file = fileList[i];
            if (_.checkFile(file.name)) {
                var ok = true;
                for (var k = 0; k < _.constant.locFileList.length; k++) {
                    var f = _.constant.locFileList[k];
                    if (file.name == f.name) {
                        ok = false;
                        break;
                    }
                }
                if (ok) {
                    _.constant.locFileList = _.constant.locFileList.concat(file);
                }
            }
            else {
                _.constant.errFileList = _.constant.errFileList.concat([file.name]);
            }
        }
        if (_.constant.locFileList.length > 0) {
            $(_.constant.fiAddrList).html("");
            for (var i = 0; i < _.constant.locFileList.length; i++) {
                var item = '<li>' + _.constant.locFileList[i].name + '</li>';
                $(_.constant.fiAddrList).append(item);
            }
        }
        if (_.constant.errFileList.length > 0) {
            var message = "";
            for (var i = 0; i < _.constant.errFileList.length - 1; i++) {
                message += _.constant.errFileList[i] + ",";
            }
            message += _.constant.errFileList[_.constant.errFileList.length - 1] + "文件格式有误，只能上传格式为";
            for (var i = 0; i < _.o.filter.length - 1; i++) {
                message += _.o.filter[i] + ", ";
            }
            message += _.o.filter[_.o.filter.length - 1];
            message += "的文件";
            alert(message);
        }

    },

    checkFile: function (fileName) {
        if (fileName == null || fileName == "") {
            return false;
        }
        var _ = this;
        if (_.o.filter.length < 1) {
            return true;
        }
        var fileOk = false;
        var sp = fileName.split(".");
        var ex = sp[sp.length - 1].toString().toLowerCase();
        for (var i = 0; i < _.o.filter.length; i++) {
            if (ex == _.o.filter[i].toString().toLowerCase()) {
                fileOk = true;
                break;
            }
        }
        return fileOk;
    },

    getFileList: function (path) {
        var _ = this;
        $.ajax({
            url: _.constant.ajaxUrl,
            data: { p: path, root: _.constant.rootPath, c: AJAXCODE.GetFileList, r: Math.random() },
            type: "POST",
            dataType: "json",
            success: function (data) {
                if (data == null || data == "") {
                    alert("返回的数据格式不正确！");
                }

                if (data.Success) {
                    $(_.constant.backPath).attr("back", data.O.BackPath ? data.O.BackPath : "");
                    $(_.constant.fileList).html(data.O.FileList ? data.O.FileList : "");
                }
                else {
                    if (data.Message != null && data.Message != "") {
                        alert(data.Message);
                    }
                }
            }
        });
    },

    toBack: function (e) {
        var _ = this;
        var back = $(e).attr("back") ? $(e).attr("back") : "";
        _.getFileList(back);
    },

    deleteFile: function (e) {
        var _ = this;
        var path = $(e).parents("li").attr("p") ? $(e).parents("li").attr("p") : "";
        if (path == "") {
            return;
        }
        if (!confirm('确定要删除"' + path + '"吗？')) {
            return;
        }

        $.ajax({
            url: _.constant.ajaxUrl,
            data: { p: path, c: AJAXCODE.CheckFolder, r: Math.random() },
            type: "POST",
            dataType: "json",
            success: function (data) {
                if (!data.Success) {
                    if (data.Message != null && data.Message != "") {
                        alert(data.Message);
                    }
                    return;
                }
                if (data.Message != null && data.Message != "") {
                    if (!confirm(data.Message)) {
                        return;
                    }
                }
                $.ajax({
                    url: _.constant.ajaxUrl,
                    data: { p: path, c: AJAXCODE.DeleteFile, r: Math.random() },
                    type: "POST",
                    dataType: "json",
                    success: function (data) {
                        if (data == null || data == "") {
                            alert("返回的数据格式不正确！");
                        }

                        if (data.Success) {
                            $(e).parents("li").remove();
                        }
                        else {
                            if (data.Message != null && data.Message != "") {
                                alert(data.Message);
                            }
                        }
                    }
                });
            }
        });
    },

    selectSingleFile: function (e) {
        var _ = this;
        var t = $(e).parents("li").attr("type") ? $(e).parents("li").attr("type") : "";
        if (t != _.constant.file) {
            return;
        }
        $(_.constant.fileList).children("li").removeClass(_.constant.curCss);
        $(e).parents("li").addClass(_.constant.curCss);
        $(_.constant.fiSelect).attr("p", $(e).parents("li").attr("p") ? $(e).parents("li").attr("p") : "");
    },

    confirmSelection: function () {
        var _ = this;
        var mod = $(_.constant.fiConfirm).attr("mod") ? $(_.constant.fiConfirm).attr("mod") : "";
        if (mod == "") {
            return;
        }
        if (mod == _.constant.mod.web) {
            var p = $(_.constant.fiUrl).val();
            if (p == null || p == "") {
                alert(_.constant.errMessage.em0);
                return;
            }
            var alt = $(_.constant.fiDesc).val() ? $(_.constant.fiDesc).val() : "";
            if (_.o.back) {
                var o = new Object();
                o.OS = new Array();
                o.OS[0] = {
                    Url: p,
                    Name: alt,
                    Icon: p
                };
                _.o.back(o);
                _.close();
            }
            else {
                if ($(_.o.dest)) {
                    if (_.checkFile(p)) {
                        $(_.o.dest).attr({
                            src: p,
                            alt: alt,
                            title: alt
                        });
                        _.close();
                    }
                    else {
                        var message = "文件" + p + "格式错误，只能选择"
                        for (var i = 0; i < _.o.filter.length - 1; i++) {
                            message += _.o.filter[i] + ", ";
                        }
                        message += _.o.filter[_.o.filter.length - 1];
                        message += "的文件";
                        alert(message);
                    }
                }
            }
        }
        else {
            _.uploadFile();
        }
    },

    select: function () {
        var _ = this;
        var p = $(_.constant.fiSelect).attr("p") ? $(_.constant.fiSelect).attr("p") : "";
        if (p == "") {
            alert(_.constant.errMessage.em0);
            return;
        }

        $(_.constant.fiUrl).val(p);
        _.closeSource();
    },

    resize: function () {
        var _ = this;
        var smod = $(_.constant.fiResize).attr("smod") ? $(_.constant.fiResize).attr("smod") : _.constant.sizeMode.min;
        //最大化
        if (smod == _.constant.sizeMode.min) {
            $(_.constant.fiResize).attr("smod", _.constant.sizeMode.max);
            $(_.constant.fiResize).html(_.constant.minimize);
            $(_.constant.fiSource).addClass("max");
            var h = $(window).height() - _.constant.subHeight;
            $(_.constant.fileList).css("height", h + "px");
            $(window).resize(function () {
                h = $(window).height() - _.constant.subHeight;
                $(_.constant.fileList).css("height", h + "px");
            });
        } //还原
        else {
            $(_.constant.fiResize).attr("smod", _.constant.sizeMode.min);
            $(_.constant.fiResize).html(_.constant.maximize);
            $(_.constant.fiSource).removeClass("max");
            $(_.constant.fileList).css("height", _.constant.minHeight);
            $(window).resize(function () {
                $(_.constant.fileList).css("height", _.constant.minHeight);
            });
        }
    },

    selectOne: function () {
        var _ = this;
        try {
            $.ajaxFileUpload({
                url: _.constant.ajaxUrl,
                fileElementId: _.constant.fiUploaderId,
                data: { id: _.constant.fiUploaderId, p: _.constant.rootPath, m: _.o.mode, c: AJAXCODE.FiUploader, r: Math.random() },
                dataType: "text",
                success: function (data) {
                    if (data == null || data == "") {
                        alert("返回的数据有误！");
                        return;
                    }
                    var result = data;
                    if (data.substr(0, 1) == "<") {
                        result = $(data).html();
                    }
                    if (result.substr(0, 1) != "{") {
                        alert("返回的数据有误！");
                        return;
                    }
                    var json = eval('(' + result + ')');
                    if (json.Success) {
                        if (_.o.back) {
                            _.o.back(json.O);
                        }
                        else {
                            if (_.o.dest && json.O.OS[0]) {
                                $(_.o.dest).attr({
                                    src: json.O.OS[0].Icon,
                                    p: json.O.OS[0].Url
                                });
                            }
                        }
                        _.close();
                    }
                    else {
                        alert(json.Message);
                    }
                }
            });
        }
        catch (ex) {
            alert(ex.message);
        }
    },

    selectMultiple: function () {
        var _ = this;
        var count = 0;
        var fd;
        var file;
        fd = new FormData();
        for (var i = 0; i < _.constant.locFileList.length; i++) {
            fd.append("fx" + i, _.constant.locFileList[i]);
        }
        fd.append("id", "fx");
        fd.append("p", _.constant.rootPath);
        fd.append("m", _.o.mode);
        fd.append("c", AJAXCODE.FiUploaderM);
        fd.append("r", Math.random());
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function (e) {
            if (xhr.readyState == 4 && xhr.status == 200) {
                var data = xhr.responseText;
                if (data == null || data == "") {
                    alert("返回的数据有误！");
                    return;
                }
                var result = data;
                if (data.substr(0, 1) == "<") {
                    result = $(data).html();
                }
                if (result.substr(0, 1) != "{") {
                    alert("返回的数据有误！");
                    return;
                }
                var json = eval('(' + result + ')');
                if (json.Success) {
                    if (_.o.back) {
                        _.o.back(json.O);
                    }
                    _.constant.locFileList = [];
                    _.close();
                }
                else {
                    alert(json.Message);
                }
            }
            else {
            }
        }
        xhr.open("POST", _.constant.ajaxUrl);
        xhr.send(fd);

    },
    uploadFile: function () {
        var _ = this;
        var brow = $.browser;
        var version = parseInt(brow.version);
        if (!_.o.multiple || brow.msie && version < 9.0) {
            _.selectOne();
        }
        else {
            _.selectMultiple();
        }
    }
};